<link rel="import" href="../../bower_components/iron-ajax/iron-ajax.html">
<link rel="import" href="../../bower_components/paper-styles/typography.html">
<link rel="import" href="../../bower_components/paper-button/paper-button.html">
<link rel="import" href="../../bower_components/paper-input/paper-textarea.html">
<link rel="import" href="../../bower_components/paper-dropdown-menu/paper-dropdown-menu.html">
<link rel="import" href="../../bower_components/neon-animation/animations/scale-up-animation.html">
<link rel="import" href="../../bower_components/neon-animation/animations/fade-out-animation.html">
<link rel="import" href="../../bower_components/paper-listbox/paper-listbox.html">
<link rel="import" href="../../bower_components/vaadin-dialog/vaadin-dialog.html">
<dom-module id="run-script-on-machine">
    <template>
        <style include="shared-styles dialogs">
        :host {
            width: 100%;
        }

        :host .btn-group {
            margin: 0 0 24px 0;
        }

        .grey {
            opacity: 0.54;
        }

        :host paper-dropdown-menu ::slotted(.dropdown-content) {
            top: 55px !important;
        }
        </style>
        <vaadin-dialog id="scriptDialogModal" theme="mist-dialog" with-backdrop>
            <template>
                <h2>Run a script</h2>
                <div class="paper-dialog-scrollable">
                    <p>
                        <span class="grey"> Choose from your existing scripts. </span>
                        <paper-dropdown-menu label="Select script" horizontal-align="left">
                            <paper-listbox slot="dropdown-content" id="scripts" attr-for-selected="value" selected="{{selectedScriptId}}" class="dropdown-content">
                                <template is="dom-repeat" items="[[scripts]]" as="script">
                                    <paper-item value="[[script.id]]">[[script.name]]</paper-item>
                                </template>
                            </paper-listbox>
                        </paper-dropdown-menu>
                    </p>
                    <p>
                        <paper-textarea label="Params" rows="3" value="{{params}}"></paper-textarea>
                    </p>
                </div>
                <div class="clearfix btn-group">
                    <paper-button on-tap="_dismissDialog">
                        Cancel
                    </paper-button>
                    <paper-button class="blue" on-tap="runScript" dialog-confirm disabled$="[[!selectedScriptId]]">
                        Run Script
                    </paper-button>
                </div>
            </template>
        </vaadin-dialog>
        <iron-ajax id="runScriptRequest" url="/api/v1/scripts/[[selectedScriptId]]" method="POST" on-response="_runScriptResponse" on-error="_runScriptError" on-request="_runScriptRequest" handle-as="xml"></iron-ajax>
    </template>
</dom-module>
<script>
Polymer({
    is: 'run-script-on-machine',

    properties: {
        items: {
            type: Array,
            notify: true
        },
        selected: {
            type: String
        },
        selectedScriptId: {
            type: Number,
            value: -1
        },
        scripts: {
            type: Array
        },
        params: {
            type: String,
            observer: '_paramsChanged'
        }
    },
    listeners: {},
    ready: function() {},
    computedSelectedScriptId: function(selected) {},
    _openDialog: function(e) {
        this.set('selected', false);
        this.set('selectedScriptId', false);
        this.set('params', '');
        this.$.scriptDialogModal.opened = true;
    },
    _dismissDialog: function(e) {
        this.$.scriptDialogModal.opened = false;
    },
    runScript: function(e) {
        var request = this.$.runScriptRequest;
        var scriptparams = this.params || '';

        console.log('runScript', request.id, items, scriptparams);

        var items = this.items.slice(0);
        var run = function(el) {
            var item = items.shift(),
                itemType,
                itemId;
            if (item.length) {
                chunks = item.split(':'),
                    itemId = chunks[2],
                    cloudId = chunks[1];
            } else {
                itemId = item.id;
                cloudId = item.cloud.id;
            }
            request.body = {
                machine_uuid: itemId,
                params: scriptparams
            }
            request.headers["Content-Type"] = 'application/json';
            request.headers["Csrf-Token"] = CSRF_TOKEN;
            request.generateRequest();

            if (items.length) {
                run(el);
            }
        }
        run(this);
    },
    _runScriptRequest: function() {
        var logMessage = 'Sending request to run script on machine.';
        this.dispatchEvent(new CustomEvent('performing-action', { bubbles: true, composed: true, detail: { log: logMessage } }));

    },
    _runScriptResponse: function(e) {
        console.log(e, e.detail);
        this.dispatchEvent(new CustomEvent('action-finished', { bubbles: true, composed: true, detail: { success: true } }));
        this.dispatchEvent(new CustomEvent('toast', { bubbles: true, composed: true, detail: { msg: 'Run script request sent successfully. Review in machine logs.', duration: 5000 } }));
        this._dismissDialog();
    },
    _runScriptError: function(e) {
        console.log(e, e.detail);
        this.dispatchEvent(new CustomEvent('action-finished', { bubbles: true, composed: true, detail: { success: false } }));

        this.dispatchEvent(new CustomEvent('toast', { bubbles: true, composed: true, detail: { msg: e.detail.xhr.response, duration: 5000 } }));

    }
});
</script>